<template>
  <div class="audio-recorder">
    <!-- 麦克风控制按钮 -->
    <button 
      id="voice-record-btn"
      class="btn voice-record-btn"
      :class="buttonClass"
      @click="toggleRecording"
      :disabled="isProcessing"
    >
      <i :class="iconClass"></i>
      <span>{{ buttonText }}</span>
    </button>
    
    <!-- 录音指示器 -->
    <div 
      v-if="isRecording" 
      class="recording-status"
    >
      <span class="recording-dot blink"></span>
      <span class="recording-text">正在录音...</span>
      <span class="recording-time">{{ recordingTime }}</span>
    </div>
    
    <!-- 音量指示器 -->
    <div class="volume-indicator">
      <div class="volume-bars">
        <div 
          v-for="i in 5" 
          :key="i"
          class="volume-bar" 
          :style="{ height: getVolumeBarHeight(i) }"
        ></div>
      </div>
      <span class="volume-text">{{ volumeLevelText }}</span>
    </div>
    
    <!-- 录音选项 -->
    <div class="recording-options">
      <button 
        class="btn btn-outline-secondary btn-sm"
        @click="toggleNoiseCancellation"
        :class="{ active: isNoiseCancellationEnabled }"
      >
        <i class="bi bi-mic-mute-fill"></i>
        <span>降噪</span>
      </button>
      <button 
        class="btn btn-outline-secondary btn-sm"
        @click="toggleEchoCancellation"
        :class="{ active: isEchoCancellationEnabled }"
      >
        <i class="bi bi-refresh"></i>
        <span>消回声</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import AudioService from '../services/AudioService.js'
import WebRTCService from '../services/WebRTCService.js'

// Props
const props = defineProps({
  autoEnable: {
    type: Boolean,
    default: false
  },
  soundThreshold: {
    type: Number,
    default: 0.05
  },
  silenceTimeout: {
    type: Number,
    default: 1500
  }
})

// Emits
const emit = defineEmits(['recording-start', 'recording-stop', 'audio-data', 'error', 'status-change'])

// 响应式数据
const isMicEnabled = ref(false)
const isRecording = ref(false)
const isProcessing = ref(false)
const buttonClass = ref('btn-success')
const buttonText = ref('点击启用麦克风')
const iconClass = ref('bi bi-mic-fill')
const volumeLevel = ref(0)
const volumeLevelText = ref('静音')
const recordingStartTime = ref(0)
const recordingTime = ref('00:00')
const recordingTimerInterval = ref(null)
const isNoiseCancellationEnabled = ref(false)
const isEchoCancellationEnabled = ref(false)

// 音频服务实例
let audioService = null
let webRTCService = null

// 计算属性 - 音量条高度
const getVolumeBarHeight = computed(() => {
  return (index) => {
    const threshold = 0.2 * index
    return volumeLevel.value >= threshold ? `${threshold * 5 * 100}%` : '0%'
  }
})

// 生命周期钩子
onMounted(() => {
  // 初始化服务 - 使用单例实例
  audioService = AudioService
  webRTCService = WebRTCService
  
  // 设置音频配置
  audioService.setConfig({
    soundThreshold: props.soundThreshold,
    silenceTimeoutMs: props.silenceTimeout,
    bufferSize: 4096,
    sampleRate: 16000
  })
  
  // 设置回调函数
  audioService.setCallback('onRecordingStart', handleRecordingStart)
  audioService.setCallback('onRecordingStop', handleRecordingStop)
  audioService.setCallback('onDataAvailable', handleAudioData)
  audioService.setCallback('onAudioAnalysed', (data) => {
    updateVolumeLevel(data.volume)
  })
  audioService.setCallback('onError', handleError)
  
  // 如果设置了自动启用，则尝试启用麦克风
  if (props.autoEnable) {
    enableMicrophone()
  }
  
  // 初始化状态
  updateStatus()
})

onUnmounted(() => {
  // 清理资源
  cleanupResources()
})

// 处理录音开始
function handleRecordingStart() {
  isRecording.value = true
  buttonClass.value = 'btn-danger recording-pulse'
  buttonText.value = '点击停止录音'
  iconClass.value = 'bi bi-stop-fill'
  
  // 记录开始时间并启动计时器
  recordingStartTime.value = Date.now()
  startRecordingTimer()
  
  emit('recording-start')
  updateStatus()
}

// 处理录音停止
function handleRecordingStop() {
  isRecording.value = false
  buttonClass.value = 'btn-outline-secondary'
  buttonText.value = '麦克风就绪'
  iconClass.value = 'bi bi-mic-fill'
  
  // 停止计时器
  stopRecordingTimer()
  
  emit('recording-stop')
  updateStatus()
}

// 处理音频数据
function handleAudioData(audioData) {
  isProcessing.value = true
  
  // 发送音频数据到父组件
  emit('audio-data', audioData)
  
  // 处理完成后重置状态
  setTimeout(() => {
    isProcessing.value = false
  }, 500)
}

// 更新音量级别显示
function updateVolumeLevel(level) {
  volumeLevel.value = level
  
  // 更新音量文本
  if (level < 0.1) {
    volumeLevelText.value = '静音'
  } else if (level < 0.3) {
    volumeLevelText.value = '小声'
  } else if (level < 0.6) {
    volumeLevelText.value = '适中'
  } else {
    volumeLevelText.value = '大声'
  }
}

// 处理错误
function handleError(error) {
  console.error('音频服务错误:', error)
  emit('error', error)
  
  // 重置状态
  if (isProcessing.value) {
    isProcessing.value = false
  }
  
  // 根据错误类型调整按钮状态
  if (error.name === 'NotAllowedError') {
    buttonText.value = '请授予麦克风权限'
    buttonClass.value = 'btn-outline-secondary'
  }
  
  updateStatus()
}

// 开始录音计时器
function startRecordingTimer() {
  // 清除之前的计时器
  stopRecordingTimer()
  
  // 设置新的计时器
  recordingTimerInterval.value = setInterval(() => {
    const now = Date.now()
    const duration = Math.floor((now - recordingStartTime.value) / 1000)
    const minutes = Math.floor(duration / 60).toString().padStart(2, '0')
    const seconds = (duration % 60).toString().padStart(2, '0')
    recordingTime.value = `${minutes}:${seconds}`
  }, 1000)
}

// 停止录音计时器
function stopRecordingTimer() {
  if (recordingTimerInterval.value) {
    clearInterval(recordingTimerInterval.value)
    recordingTimerInterval.value = null
    recordingTime.value = '00:00'
  }
}

// 启用麦克风
async function enableMicrophone() {
  try {
    await audioService.enableMicrophone()
    isMicEnabled.value = true
    buttonClass.value = 'btn-outline-secondary'
    buttonText.value = '麦克风就绪'
    updateStatus()
  } catch (error) {
    handleError(error)
  }
}

// 禁用麦克风
function disableMicrophone() {
  audioService.disableMicrophone()
  isMicEnabled.value = false
  isRecording.value = false
  buttonClass.value = 'btn-success'
  buttonText.value = '点击启用麦克风'
  iconClass.value = 'bi bi-mic-fill'
  
  // 停止计时器
  stopRecordingTimer()
  
  updateStatus()
}

// 切换录音状态
function toggleRecording() {
  if (isProcessing.value) {
    return // 处理中时不允许操作
  }
  
  if (isRecording.value) {
    // 停止录音
    audioService.stopRecording()
  } else if (isMicEnabled.value) {
    // 开始录音
    audioService.startRecording()
  } else {
    // 启用麦克风
    enableMicrophone()
  }
}

// 切换降噪功能
function toggleNoiseCancellation() {
  isNoiseCancellationEnabled.value = !isNoiseCancellationEnabled.value
  
  // 更新音频服务配置
  audioService.setConfig({
    noiseCancellation: isNoiseCancellationEnabled.value
  })
  
  console.log('降噪功能已', isNoiseCancellationEnabled.value ? '启用' : '禁用')
}

// 切换回声消除功能
function toggleEchoCancellation() {
  isEchoCancellationEnabled.value = !isEchoCancellationEnabled.value
  
  // 更新音频服务配置
  audioService.setConfig({
    echoCancellation: isEchoCancellationEnabled.value
  })
  
  console.log('回声消除功能已', isEchoCancellationEnabled.value ? '启用' : '禁用')
}

// 更新状态并通知父组件
function updateStatus() {
  emit('status-change', {
    isMicEnabled: isMicEnabled.value,
    isRecording: isRecording.value,
    isProcessing: isProcessing.value,
    volumeLevel: volumeLevel.value
  })
}

// 清理资源
function cleanupResources() {
  // 停止计时器
  stopRecordingTimer()
  
  // 清理音频服务
  if (audioService) {
    audioService.cleanup() // 使用cleanup方法清理所有资源和回调
    audioService = null
  }
  
  // 重置状态
  isMicEnabled.value = false
  isRecording.value = false
  isProcessing.value = false
  buttonClass.value = 'btn-success'
  buttonText.value = '点击启用麦克风'
  iconClass.value = 'bi bi-mic-fill'
}

// 暴露方法给父组件
defineExpose({
  enableMicrophone,
  disableMicrophone,
  toggleRecording,
  isMicEnabled,
  isRecording
})
</script>

<style scoped>
.audio-recorder {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  margin: 0 auto;
}

.voice-record-btn {
  width: 100%;
  padding: 12px 20px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 25px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid transparent;
}

.voice-record-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.voice-record-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

button i {
  margin-right: 8px;
  font-size: 18px;
}

.recording-status {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;
  padding: 8px 15px;
  background-color: rgba(220, 53, 69, 0.1);
  border-radius: 25px;
  border: 1px solid rgba(220, 53, 69, 0.2);
}

.recording-dot {
  width: 10px;
  height: 10px;
  background-color: #dc3545;
  border-radius: 50%;
  margin-right: 8px;
  box-shadow: 0 0 10px rgba(220, 53, 69, 0.5);
}

.recording-text {
  font-size: 0.9rem;
  color: #dc3545;
  font-weight: 500;
}

.recording-time {
  font-size: 0.9rem;
  color: #dc3545;
  font-weight: 500;
  margin-left: auto;
  font-family: 'Courier New', monospace;
}

.blink {
  animation: blink 1s infinite;
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.3; }
  100% { opacity: 1; }
}

.recording-pulse {
  animation: pulse 1.5s infinite;
  border-color: #dc3545 !important;
}

@keyframes pulse {
  0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.4); }
  50% { transform: scale(1.05); box-shadow: 0 0 0 10px rgba(220, 53, 69, 0); }
  100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
}

.volume-indicator {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.volume-bars {
  display: flex;
  justify-content: center;
  align-items: end;
  gap: 6px;
  height: 50px;
  margin-bottom: 8px;
}

.volume-bar {
  width: 8px;
  background-color: #4361ee;
  border-radius: 4px;
  transition: height 0.2s ease;
  animation: volumeAnimation 1.5s ease-in-out infinite;
}

.volume-bar:nth-child(2) { animation-delay: 0.1s; }
.volume-bar:nth-child(3) { animation-delay: 0.2s; }
.volume-bar:nth-child(4) { animation-delay: 0.3s; }
.volume-bar:nth-child(5) { animation-delay: 0.4s; }

@keyframes volumeAnimation {
  0%, 100% { transform: scaleY(1); }
  50% { transform: scaleY(1.1); }
}

.volume-text {
  font-size: 0.85rem;
  color: #6c757d;
  font-weight: 500;
}

.recording-options {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.recording-options button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 0.85rem;
  transition: all 0.3s ease;
}

.recording-options button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.recording-options button.active {
  background-color: #4361ee !important;
  color: white !important;
  border-color: #4361ee !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .audio-recorder {
    padding: 12px;
    max-width: 100%;
  }
  
  .voice-record-btn {
    padding: 10px 16px;
    font-size: 14px;
  }
  
  .recording-options {
    gap: 8px;
  }
  
  .recording-options button {
    padding: 6px 12px;
    font-size: 0.8rem;
  }
}
</style>